<?php
require_once 'HistoricoDoAluno.php';
require_once 'Catalogo.php';

class ControladorServidorDados {
    const urlServidorDados = 'http://localhost:51000/';
    const URL_HISTORICO = 'http://143.106.16.163:51000/?serv=h&ra=$RA';
    const URL_CATALOGO = 'http://143.106.16.163:51000/?serv=c&cod=$CURSO';
    const URL_DISCIPLINA = 'http://143.106.16.163:51000/?serv=d&s=$SIGLA';
    
    public function __construct(){
    
    }
    
    private function getData($url){
        $curler = curl_init();
        curl_setopt($curler, CURLOPT_URL, $url);
        curl_setopt($curler, CURLOPT_HEADER, FALSE);
        curl_setopt($curler, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curler, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 ( .NET CLR 3.5.30729)");
        
        $resposta = curl_exec($curler);
        
        try {
            $xml = @new SimpleXMLElement($resposta);
        } catch (Exception $e) { 
            echo "bad request: ". $url;
            die;
        }
        
        curl_close($curler);
        
        return $xml;
    }
    
    public function obterDados($ra){
        $historicoAluno = $this->obterHistorico($ra);
        
        $catalogoAluno = $this->obterCatalogo($historicoAluno->codigoCurso, $historicoAluno->modalidade);
        
        foreach ($catalogoAluno->obrigatorias as $i => $disciplinaObrigatoria) {
            $Disciplina = $this->obterDisciplina($disciplinaObrigatoria->sigla);
            $catalogoAluno->obrigatorias[$i] = $Disciplina;
        }
        
        $temp = json_decode($historicoAluno->toJson(), true);
        
        $temp['allocation'] = json_decode($catalogoAluno->toJson());
        
        return json_encode($temp);
    }
    
    public function obterHistorico($ra){
        
        $url = str_replace('$RA', $ra, self::URL_HISTORICO);
        $xml = $this->getData($url);
        
        $historico = new HistoricoDoAluno($xml);
        
        return $historico;
        
    }
    
    public function obterCatalogo($codigo, $modalidade){

        $url = str_replace('$CURSO', $codigo, self::URL_CATALOGO);
        $xml = $this->getData($url);
        
        $catalogo = new Catalogo($xml, $modalidade);
        
        return $catalogo;
    }
    
    public function obterDisciplina($sigla){
        $url = str_replace('$SIGLA', urlencode($sigla), self::URL_DISCIPLINA);
        $xml = $this->getData($url);
        
        $disciplina = new Disciplina($xml);
        
        return $disciplina;
    }
}
    